package com.gzit.view.tag;

import android.content.Context;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import com.gzit.R;

public class TagGroupView extends View {

	private static final String TAG = "TagGroupView";

	// tag之间的默认间隔空间
	private static final int DEF_MARGIN_BETWEEN_TAG = 10;

	// TAG的padding
	private static final int DEF_TAG_PADDING = 10;

	// 默认的背景
	private static final int DEF_BG_COLOR = Color.WHITE;

	private Drawable delIconBitmap;

	private float tagMargin = DEF_MARGIN_BETWEEN_TAG;
	private int bgColor = DEF_BG_COLOR;
	private float tagPadding = DEF_TAG_PADDING;

	private float tagTextSize;
	private Paint textPaint;

	// 是否处于删除模式下
	private boolean deleteMode;

	private Paint selPaint = new Paint();
	private Paint bgPaint = new Paint();
	{
		selPaint.setColor(Color.BLACK);
		bgPaint.setColor(Color.BLUE);

	}

	private TagDataAdapter adapter;

	// 位置所占领的高度
	private float CHAR_HEIGHT = 0;

	public TagGroupView(Context context) {
		super(context);
	}

	public TagGroupView(Context context, AttributeSet attrs) {
		super(context, attrs);

		TypedArray arr = context.obtainStyledAttributes(attrs,
				R.styleable.TagGroupView);
		tagTextSize = arr.getDimension(R.styleable.TagGroupView_tag_textSize,
				10);
		bgColor = arr.getColor(R.styleable.TagGroupView_tag_bgcolor,
				Color.WHITE);
		tagMargin = arr.getDimension(R.styleable.TagGroupView_tag_margin,
				DEF_MARGIN_BETWEEN_TAG);
		tagPadding = arr.getDimension(R.styleable.TagGroupView_tag_padding,
				DEF_TAG_PADDING);

		arr.recycle();

		// 用于测量标签框大小
		textPaint = new Paint();
		textPaint.setTextSize(tagTextSize);
		textPaint.setAntiAlias(true);
		textPaint.setTextAlign(Align.CENTER);
		textPaint.setFakeBoldText(true);
		textPaint.setColor(Color.WHITE);

		// 可删除的图标
		delIconBitmap = context.getResources().getDrawable(
				R.drawable.gzit_del_icon);

		// 以中文文字为准（英文文字会矮一些）
		CHAR_HEIGHT = this.messureTag("牛")[1];

	}

	// 计算tag的坐标等信息信息
	private float[] messureTag(String content) {

		Rect rect = new Rect();
		textPaint.getTextBounds(content, 0, content.length(), rect);

		// 每个tag额外的padding大小
		float extraPadding = tagPadding * 2;
		return new float[] { rect.width() + extraPadding,
				rect.height() + extraPadding };

	}

	private void updateTagViewStatus() {

		if (this.adapter == null)
			return;

		int width = this.getWidth();
		int line = 0;
		float occupiedWidth = 0;
		for (TagItem tag : this.adapter.getTags()) {

			// 设置TAG绘制的画笔
			tag.setBgPaint(bgPaint);
			tag.setSelPaint(selPaint);
			tag.setTextPaint(textPaint);

			// 测量TAG的大小
			float[] size = this.messureTag(tag.getContent());

			float tagLen = size[0];
			float tagHeight = CHAR_HEIGHT;

			tag.setWidth(tagLen);
			tag.setHeight(tagHeight);

			// 计算坐标
			if (tagLen > width) { // 一个tag占多行的情况
			}

			float restWidth = width - occupiedWidth - this.tagMargin;
			if (restWidth < tagLen) {// 剩下的空间不够放tag,移动到下一行

				line++;
				tag.setX(this.tagMargin);
				tag.setY(line * tagHeight + line * this.tagMargin
						+ this.tagMargin);

				occupiedWidth = this.tagMargin + tagLen;
				continue;

			}

			tag.setX(occupiedWidth + this.tagMargin);
			tag.setY(line * tagHeight + line * this.tagMargin + this.tagMargin);

			occupiedWidth += (tagLen + this.tagMargin);

		}

	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

		int measureWidth = measureWidth(widthMeasureSpec);

		setMeasuredDimension(measureWidth,
				measureHeight(heightMeasureSpec, measureWidth));
	}

	private int measureWidth(int measureSpec) {
		int suppliedWidth = MeasureSpec.getSize(measureSpec);
		Log.i(TAG, "suppliedWidth:" + suppliedWidth);
		Log.i(TAG, "width mode:" + DebugTool.getMessureMode(measureSpec));
		return suppliedWidth;
	}

	private int measureHeight(int measureSpec, int width) {

		// int suppliedHeight = MeasureSpec.getSize(measureSpec);
		// Log.i(TAG, "suppliedHeight:" + suppliedHeight);
		// Log.i(TAG, "height mode:" + DebugTool.getMessureMode(measureSpec));

		// 通过textSize,padding以及margin等计算整体区域所占的高度

		if (this.adapter == null)
			return 0;

		float oneTagHeight = 0;

		// int width = this.getWidth();
		// int width = width;

		int line = 0;
		float occupiedWidth = 0;
		for (TagItem tag : this.adapter.getTags()) {

			// 测量TAG的大小
			float[] size = this.messureTag(tag.getContent());

			float tagLen = size[0];
			float tagHeight = size[1];

			oneTagHeight = tagHeight;

			// 计算坐标
			if (tagLen > width) { // 一个tag占多行的情况
			}

			float restWidth = width - occupiedWidth - this.tagMargin;
			if (restWidth < tagLen) {// 剩下的空间不够放tag,移动到下一行
				occupiedWidth = this.tagMargin + tagLen;
				line++;
				continue;
			}

			occupiedWidth += (tagLen + this.tagMargin);

		}

		int height = (int) (oneTagHeight + tagMargin * 2) * (line + 1);
		Log.i(TAG, "所占领的高度:" + height);

		// 计算整个区域的高度
		return height;

	}

	private void tagSelectDetected(float x, float y) {

		for (TagItem tag : this.adapter.getTags()) {
			if (tag.isPointInDeleteArea(x, y, this.delIconBitmap)) {
				if (this.tagSelectedListener != null) {
					tagSelectedListener.tagDelete(tag);
				}

				// TD:可以优化局部重绘
				this.invalidate();
				return;
			}

		}

	}

	public boolean onTouchEvent(MotionEvent event) {

		if (this.isInDeleteMode()) {// 在删除模式下，才检测点击事件
			float x = event.getX();
			float y = event.getY();
			this.tagSelectDetected(x, y);

			Log.i(TAG, "x:" + x + " y:" + y);
		}

		return super.onTouchEvent(event);
	}

	private void drawBackground(Canvas canvas) {
		Paint paint = new Paint();
		paint.setAntiAlias(true);
		paint.setColor(bgColor);
		canvas.drawRect(0, 0, this.getWidth(), this.getHeight(), paint);
	}

	private void drawTagViews(Canvas canvas) {

		for (TagItem tag : this.adapter.getTags()) {
			tag.draw(canvas, this);
		}

	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		this.updateTagViewStatus();
		this.drawBackground(canvas);
		this.drawTagViews(canvas);
	}

	public TagDataAdapter getAdapter() {
		return adapter;
	}

	public void setAdapter(TagDataAdapter adapter) {
		this.adapter = adapter;
		this.adapter.registerDataSetObserver(new DataSetObserver() {
			public void onChanged() {

				TagGroupView.this.invalidate();
				TagGroupView.this.requestLayout();
			}

			public void onInvalidated() {

				TagGroupView.this.invalidate();
			}

		});
	}

	public Drawable getDelIconBitmap() {
		return delIconBitmap;
	}

	public void setDelIconBitmap(Drawable delIconBitmap) {
		this.delIconBitmap = delIconBitmap;
	}

	// tag选时的事件
	private OnTagSelectListener tagSelectedListener;

	public OnTagSelectListener getTagSelectedListener() {
		return tagSelectedListener;
	}

	public boolean isInDeleteMode() {
		return deleteMode;
	}

	public void setDeleteMode(boolean deleteMode) {
		if (this.deleteMode != deleteMode) {// 模式发生改变时重绘标签组件
			this.deleteMode = deleteMode;
			this.invalidate();
		}

	}

	public void setTagSelectedListener(OnTagSelectListener tagSelectedListener) {
		this.tagSelectedListener = tagSelectedListener;
	}

	public static interface OnTagSelectListener {

		void tagDelete(TagItem item);

		void tagAdd(TagItem item);

		void tagSelected(TagItem item);

	}

}
